package com.example.chatapp11;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.Socket;


public class SocketThread extends Thread{
 Handler mainHandler;
 Socket socket;
 OutputStream outputStream;
 public static Handler revhandler;
 private String serverIp;
 private int serverPort;
 private String userNickname;
 
 public SocketThread(Handler handler, String ip, int port, String nickname)
 {
  mainHandler=handler;
  this.serverIp = ip;
  this.serverPort = port;
  this.userNickname = nickname;
 }
 @Override
 public void run() {//线程启动会自动运行
  try {
   socket=new Socket(serverIp, serverPort);
   //扩展作业
   //1.连接服务器的ip地址 可变
   //2.在发送的消息加上昵称
   //3.消息列表的不同消息不同显示效果
   System.out.println("服务器连接成功！");
   //写入数据
   outputStream=socket.getOutputStream();
   outputStream.write((userNickname + " 加入了聊天室！"+"\n").getBytes("utf-8"));
   //启动子线程用于接收服务器的消息
   new Thread()
   {
    @Override
    public void run() {
     try {
      BufferedReader bReader = new BufferedReader(new
              InputStreamReader(socket.getInputStream(),"utf-8"));;
      String content=null;
      while((content=bReader.readLine())!=null)
      {
       System.out.println("来自服务器的消息："+content);
       //发给 UI 线程显示
       Message msg=new Message();
       msg.what=2;
       msg.obj=content;
       mainHandler.sendMessage(msg);
      }
     }catch (IOException e) {
      throw new RuntimeException(e);
     }
    }
   }.start();
// BufferedReader bReader=new BufferedReader(new
   new InputStreamReader(socket.getInputStream(),"utf-8");
// String clientinfo=bReader.readLine();
// System.out.println("来服务器的消息："+clientinfo);
  } catch (IOException e) {
   throw new RuntimeException(e);
  }
  //创建处理者，用于接收 UI 线程的消息，并通过 Socket 发送
  Looper.prepare();
  revhandler=new Handler()
  {
   @Override
   public void handleMessage(@NonNull Message msg) {
    if(msg.what==1)
    {
     try {
      System.out.println(msg.obj.toString());
      outputStream=socket.getOutputStream();
      outputStream.write((msg.obj.toString()+"\n").getBytes("utf-8"));
      System.out.println("发送成功！");
     } catch (IOException e) {
      throw new RuntimeException(e);
     }
    }
   }
  };
  Looper.loop();
 }
}